package cn.yomigaeri.signal.service.impl;

import cn.yomigaeri.common.entity.dto.SignalDTO;
import cn.yomigaeri.common.entity.po.Rule;
import cn.yomigaeri.common.entity.vo.SignalVO;
import cn.yomigaeri.common.json.JacksonObjectMapper;
import cn.yomigaeri.signal.client.WarnClient;
import cn.yomigaeri.signal.service.GetSignalService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: UploadSignalServiceImpl
 * @Package: cn.yomigaeri.signal.service.impl
 * @Description:
 * @Author Yomigaeri
 * @Create 2025/6/4 16:14
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GetSignalServiceImpl implements GetSignalService {

    private final RedisTemplate<String, Object> redisTemplate;
//    private final StringRedisTemplate stringRedisTemplate;
//    private final Cache<String, String> caffeineCache;
    private final WarnClient warnClient;


    @Override
    public SignalVO getSignal(Long carId) {
        List<SignalDTO> signals = new ArrayList<>();
        String key = "SignalOfCarId:" + carId + ":";
        try {
//            改为从 Caffeine 获取 warnIds
//            String warnIds = caffeineCache.getIfPresent("warnId");
//            String warnIds = stringRedisTemplate.opsForValue().get("warnId");
            Set<Integer> warnIds = warnClient.getRules().stream().map(Rule::getWarnId).collect(Collectors.toSet());
            for (Integer warnId : warnIds) {
                Object obj = redisTemplate.opsForValue().get(key + warnId);
                if (obj instanceof Map) {
                    signals.add(new JacksonObjectMapper().convertValue(obj, SignalDTO.class));
                }
            }
            SignalVO signalVO = new SignalVO();
            signalVO.setSignals(signals);
            return signalVO;
        } catch (Exception e) {
            log.error("从Redis中获取对象失败");
            return null;
        }
    }
}
